<template>
  <!-- 可选择关键字的输入框 -->
  <div class="editable boxs"  :id="'editAble' + id">
    <div v-html="showStr" contenteditable=“true” class="editAbleIn boxs"></div>
    <ul v-show="showKeyState" @mouseleave="showKeyState = false" :ref="'keyList' + id"
      class="keywordsList bgf bshadow cursor boxs" contenteditable="false">
      <li v-for="(item, index) in showWorldList"
      @click="selectWorld(item)" class="ellipsis"
          :key="index">{{item}}</li>
    </ul>
  </div>
</template>

<script>
export default {
  props: {
    // 输入框id，页面多个输入框时，使用不同id
    id: {
      type: String,
      required: true
    },
    // 模板字符串
    temStr: {
    }
  },
  data () {
    return {
      // 显示字符串
      showStr: '',
      // 关键字列表
      keyList: [],
      // 用于显示的关键字
      showWorldList: [],
      // 当前字符串
      cStr: '',
      // 当前字符串在数组中位置
      cStrIndex: 0,
      // 当前元素
      cEle: '',
      // 显示选择关键字列表
      showKeyState: false
    }
  },
  methods: {
    // 字符串编译成html
    getHtml () {
      const that = this
      // 换行处理
      this.showStr = this.showStr.replace(/\r\n/g, '<br>')
      let i = 0
      this.showStr = this.showStr.replace(/\[(.*?)\]/g, (text, result) => {
        // console.log(text, result)
        // 存贮关键字
        that.keyList.push(result)
        i++
        // 未选择关键字时默认用第一个
        if (result.indexOf('@') === -1) {
          const index = result.indexOf('|')
          return `<span index="${i}" contenteditable="false" class="clr_main cursor">${result.substr(0, index)}</span>`
        } else {
          // 关键字位置
          const index0 = result.indexOf('@')
          // 去掉关键字前面字符
          const str = result.substr(index0 + 1)
          // 找到第一个关键字分割
          const index1 = str.indexOf('|')
          let str0 = ''
          if (index1 === -1) {
            str0 = str
          } else {
            str0 = str.substr(0, index1)
          }
          return `<span index="${i}" contenteditable="false"  class="clr_main cursor">${str0}</span>`
        }
      })
      this.$nextTick(function () {
        this.worldIndex()
      })
    },
    // 关键字显示位置  左右距离还未计算
    worldIndex () {
      const that = this
      // 事件绑定
      const worlds = document.querySelectorAll('#editAble' + this.id + ' .clr_main')
      worlds.forEach(n => {
        n.onmouseenter = e => {
          // 设置显示的关键字
          const eIndex = n.getAttribute('index')
          that.cStrIndex = eIndex - 1
          that.cStr = that.keyList[that.cStrIndex]
          that.cEle = n
          const str = that.keyList[eIndex - 1].replace('@', '')
          that.showWorldList = str.split('|')
          that.showKeyState = true
          // 设置关键字显示位置
          that.$nextTick(() => {
            const keyList = that.$refs['keyList' + that.id]
            // 父元素宽度
            const parentWidth = document.getElementById('editAble' + that.id).clientWidth
            // 关键字列表宽度
            const keyWidth = keyList.clientWidth
            // 元素左边距离
            const offsetLeft = n.offsetLeft
            // 显示的关键字长度
            const selfWidth = n.clientWidth
            keyList.style.top = n.offsetTop + 14 + 'px'
            keyList.style.left = 'inhert'
            keyList.style.right = 'inhert'
            if (parentWidth === keyWidth) {
              keyList.style.left = 0
            } else if ((parentWidth - offsetLeft) >= keyWidth) {
              keyList.style.left = offsetLeft + 'px'
            } else if ((parentWidth - offsetLeft) < keyWidth) {
              keyList.style.right = offsetLeft + selfWidth - keyWidth + 'px'
            }
          })
        }
      })
    },
    // 关键字选择事件
    selectWorld (str) {
      this.cEle.innerText = str
      const newStr = this.cStr.replace('@', '').replace(str, '@' + str)
      this.keyList[this.cStrIndex] = newStr
      this.cStr = newStr
      this.showKeyState = false
      // console.log(this.keyList)
      // 最终获取字符串
      this.getTemStr(this.id)
    },
    // 最终获取字符串 待引入jquery后完成
    getTemStr (id) {
      // 1.获取输入框内的html
      // 2.将clr_main全部更换成对应index的关键字
      // 3.获取text
      const that = this
      const uls = document.querySelectorAll('#editAble' + id + ' .clr_main')
      let editHtml = document.querySelectorAll('#editAble' + id + ' .editAbleIn')[0].innerHTML
      uls.forEach((item, index) => {
        editHtml = editHtml.replace(item.outerHTML, '[' + that.keyList[index] + ']')
      })
      // console.log(editHtml)
      this.showWorldList = []
      this.$emit('getText', {
        text: editHtml,
        id: this.id
      })
    },
    // 清空输入内容
    clearInput () {
      document.querySelectorAll('#editAble' + this.id + ' .editAbleIn')[0].innerHTML = ''
      this.keyList = []
      this.cStr = ''
      this.showWorldList = []
      this.cStrIndex = 0
      this.cEle = ''
    }
  },
  mounted () {
    this.showStr = this.temStr || ''
    this.getHtml()
  }
}
</script>

<style lang="less" scoped>
@import '../../style/variable.less';
.editable{
  position:relative;
  width: 100%;
  height: 100%;
  margin: 0 auto;
}
.editAbleIn{
  width: 100%;
  height: 100%;
  outline: 0;
  border: 1px solid #a0b3d6;
  word-wrap: break-word;
  overflow-x: hidden;
  overflow-y: auto;
  line-height: 28px;
  padding: 5px;
}
.keywordsList{
  position: absolute;
  white-space: nowrap;
  padding: 5px 0;
  max-width: 100%;
}
.keywordsList li{
  padding: 0 10px;
  max-width: 100%;
}
.keywordsList li:hover{
  color: @clr_main;
}
</style>
